/**
 * Created with IntelliJ IDEA.
 * Description：
 * User：user
 * DATE:2021-11-14
 * Time:14:10
 */
class  BinarySearchTree{
    static class TreeNode{
        public int val;
        public  TreeNode left;
        public TreeNode right;
        public TreeNode(int val){
            this.val = val;
        }
    }
    public  TreeNode root;
    public  TreeNode findNode(int key){
        if(root == null)return null;
        TreeNode cur = root;
        while (cur != null){
            if(cur.val < key){
                cur = cur.right;
            }else if(cur.val == key){
                return  cur;
            }else {
                cur = cur.left;
            }
        }
        return  null;
    }
    public void insert(int key){
        TreeNode treeNode = new TreeNode(key);
        if(root == null){
            root = treeNode;
            return;
        }
       //如果有这个结点就不能插入// 找到合适的位置同时要能连接上就需要添加父节点记录位置
        TreeNode parent = null;
        TreeNode cur = root;
        while (cur != null){
            if(cur.val < key){
                parent = cur;
                cur = cur.right;
            }else if(cur.val == key){
                return;
            }else {
                parent = cur;
                cur = cur.left;
            }
        }
        if(parent.val < key){
            parent.right = treeNode;
        }else {
            parent.left = treeNode;
        }
    }


    public void remove(int key){
        //找到有没有要删除的结点
        //找到删除的结点  删除之后需要拼接前后结点
        if(root == null)return;
        TreeNode parent = null;
        TreeNode cur = root;
        while (cur != null){
            if(cur.val < key){
                parent = cur;
                cur = cur.right;
            }else if(cur.val == key){
                removeNode(parent,cur);
            }else{
                parent = cur;
                cur = cur.left;
            }
        }
    }

    private void removeNode(TreeNode parent,TreeNode cur){
        if(cur.left == null){
            if(cur == root){
                root = root.right;
            }else if(cur == parent.left){
                parent.left = cur.right;
            }else{
                parent.right = cur.right;
            }
        }else  if(cur.right == null){
            if(cur == root){
                root = root.left;
            }else if(cur == parent.left){
                parent.left = cur.left;
            }else{
                parent.right = cur.left;
            }
        }else{
            TreeNode tp = cur;
            TreeNode tar = cur.right;
            while (tar.left != null){
                tp = tar;
                tar = tar.left;
            }
            cur.val = tar.val;
            if(tar == tp.left){
                tp.left = tar.right;
            }else{
                tp.right = tar.right;
            }
        }
    }
}
public class Test {
}
